package com.easylinkin.linkappapi.openapi.util;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.openapi.dto.SystemDockInfo;
import com.easylinkin.linkappapi.openapi.dto.SystemDocking;
import com.easylinkin.linkappapi.openapi.dto.systemDock.ResultDTO;
import com.easylinkin.linkappapi.openapi.dto.systemDock.TokenDTO;
import com.easylinkin.linkappapi.openapi.mapper.SystemDockInfoMapper;
import com.easylinkin.linkappapi.openapi.mapper.SystemDockingMapper;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DataSyncUtil implements Runnable {

    private static final Logger logger = LoggerFactory.getLogger(DataSyncUtil.class);

    private SystemDockingMapper systemDockingMapper;

    private SystemDockInfoMapper infoMapper;

    private String data;

    private String url;

    private String tenantId;

    public DataSyncUtil(SystemDockingMapper systemDockingMapper, SystemDockInfoMapper infoMapper, String data, String url,
                        String tenantId) {
        this.systemDockingMapper = systemDockingMapper;
        this.infoMapper = infoMapper;
        this.data = data;
        this.url = url;
        this.tenantId = tenantId;
    }


    @SneakyThrows
    @Override
    public void run() {

        logger.info("DataSyncUtil 开始执行，url:" + url + ",data:" + data);
        //获取相应的token信息
        QueryWrapper<SystemDocking> qw = new QueryWrapper<>();
        //固定吧。
        qw.eq("sys_name", "临空港安全文明智慧监管平台");
        qw.eq("tenant_id", tenantId);
        List<SystemDocking> list = systemDockingMapper.selectList(qw);
        String response = "";
        ResultDTO responseDto = new ResultDTO();
        if (list != null && list.size() > 0) {
            SystemDocking docking = list.get(0);
            String path = docking.getUrl() + url;
            //非测试环境，替换掉实名制中的项目名称和标段信息
            if (!docking.getUrl().contains("https://syyzw.szridge.com:9289") || !docking.getSecret().equals("whzh5489sw1")) {
                data = data.replace("cookie测试项目", "吴家山四中改扩建工程").replace("cookie测试标段", "1标段");
            }

            if (StringUtils.isBlank(docking.getToken())) {
                //token为空，获取token
                doLogin(docking);
            } else {
                //上传信息
                response = HttpClientUtil.doPostToken(path, data, docking.getToken());
                responseDto = new Gson().fromJson(response, ResultDTO.class);
                //存储请求流水记录
                saveInfo(response, data, path);
                if (responseDto.getStatus() == 403) {

                    logger.info("token过期，重新获取token。。。。");
                    //token过期，重新登录获取token
                    doLogin(docking);
                }
            }
        }

        logger.info("DataSyncUtil执行结束：" + response);
    }

    /**
     * 存储请求信息
     *
     * @return
     */
    private void saveInfo(String response, String data, String path) {

        logger.info("DataSyncUtil 开始存储请求信息到systemDocnInfo：" + response);
        SystemDockInfo info = new SystemDockInfo();

        info.setCode(response);
        info.setData(data);
        info.setUrl(path);
        info.setSysname("临空港安全文明智慧监管平台");
        info.setCreateTime(new Date());

        //infoMapper.insert(info);
    }

    private void doLogin(SystemDocking docking) throws IOException {

        logger.info("doLogin----");

        String path = docking.getUrl() + "/assessHardware/client/login";
        Map<String, Object> map = new HashMap<>();
        map.put("appKey", docking.getAppid());
        map.put("appSecret", MD5Util.getMD5(docking.getSecret()));
        String response = HttpClientUtil.doPost(path, JSONObject.toJSONString(map));
        ResultDTO responseDto = new Gson().fromJson(response, ResultDTO.class);
        //存储请求流水记录
        saveInfo(response, JSONObject.toJSONString(map), path);
        //请求成功
        if (responseDto.getStatus() == 200) {
            TokenDTO tokenDTO = new Gson().fromJson(responseDto.getData().toString(), TokenDTO.class);

            docking.setToken(tokenDTO.getToken());
            docking.setRefreshToken(tokenDTO.getRefreshToken());
            //更新token信息
            systemDockingMapper.updateById(docking);
            //继续上传信息
            path = docking.getUrl() + url;
            response = HttpClientUtil.doPostToken(path, data, docking.getToken());
            //存储请求流水记录
            saveInfo(response, data, path);
        }

        logger.info("response:" + response);
        //return responseDto;
    }
}
